<template>
  <div class="app-container">
    <el-card class="query-card" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="友链名称" prop="linkName">
          <el-input
            v-model="queryParams.linkName"
            placeholder="请输入名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input
            v-model="queryParams.linkUrl"
            placeholder="请输入链接地址"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="站长邮箱" prop="email">
          <el-input
            v-model="queryParams.email"
            placeholder="请输入站长邮箱"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="友链状态" prop="linkStatus">
          <el-select v-model="queryParams.linkStatus" placeholder="请选择" clearable size="small">
            <el-option
              v-for="dict in dict.type.bl_link_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

    </el-card>
    <el-card class="table-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['blog:link:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['blog:link:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['blog:link:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['blog:link:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <vxe-table
        :loading="loading"
        resizable
        :row-config="{isHover: true,height: 90}"
        :data="linkList"
        @checkbox-all="handleSelectionChange"
        @checkbox-change="handleSelectionChange"
        :class="showSearch ? 'table-container' : 'table-container-full' "
      >
        <vxe-column type="checkbox" min-width="60" fixed="left" align="center"></vxe-column>
        <vxe-column title="序号" align="center" type="seq" min-width="80"/>
        <vxe-column field="linkIconUrl" title="网站图标" min-width="120" align="center">
          <template slot-scope="scope">
            <image-preview :src="scope.row.linkIconUrl" :width="60" :height="60"/>
          </template>
        </vxe-column>
        <vxe-column title="友链名称" align="center" field="linkName" min-width="180"/>
        <vxe-column title="链接地址" align="center" field="linkUrl" min-width="200"/>
        <vxe-column title="站长邮箱" align="center" field="email" min-width="150"/>
        <vxe-column title="友链状态" align="center" field="linkStatus" min-width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.bl_link_status" :value="scope.row.linkStatus"/>
          </template>
        </vxe-column>
        <vxe-column title="显示排序" align="center" field="orderNum" min-width="100"/>
        <vxe-column title="备注" align="center" field="remark" min-width="200"/>
        <vxe-column title="操作" align="center" fixed="right" min-width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['blog:link:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['blog:link:remove']"
            >删除
            </el-button>
          </template>
        </vxe-column>
      </vxe-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改友情链接对话框 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" v-if="dialogVisible" width="50%" v-drag-zoom append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="网站图标">
              <image-upload :visible.sync="dialogVisible" @setImageUrl="setImageUrl" :limit="1" :file-size="5"
                            :file-path="upload.path" v-model="form.linkIconUrl"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="友链名称" prop="linkName">
              <el-input v-model="form.linkName" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接地址" prop="linkUrl">
              <el-input v-model="form.linkUrl" placeholder="请输入链接地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站长邮箱" prop="status">
              <el-input v-model="form.email" placeholder="请输入站长邮箱"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="友链状态" prop="linkStatus">
              <el-select v-model="form.linkStatus" placeholder="请选择友链状态">
                <el-option
                  v-for="dict in dict.type.bl_link_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLink, getLink, delLink, addLink, updateLink } from '@/api/blog/link'
import { getToken } from '@/utils/auth'

export default {
  name: 'Link',
  dicts: ['bl_link_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 友情链接表格数据
      linkList: [],
      // 弹出层标题
      title: '',
      // 友链状态弹出层
      dialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        linkName: null,
        linkUrl: null,
        linkStatus: null,
        email: null
      },
      // 上传文件路径
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的文件夹
        path: '/blog/link-icon',
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/file/file/upload'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询友情链接列表 */
    getList() {
      this.loading = true
      listLink(this.queryParams).then(response => {
        this.linkList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.dialogVisible = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        linkName: null,
        linkUrl: null,
        createTime: null,
        updateTime: null,
        linkStatus: null,
        version: null,
        delFlag: null,
        createBy: null,
        updateBy: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(row) {
      this.ids = row.records.map(item => item.id)
      this.single = row.records.length !== 1
      this.multiple = !row.records.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.dialogVisible = true
      this.title = '添加友情链接'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getLink(id).then(response => {
        this.form = response.data
        this.dialogVisible = true
        this.title = '修改友情链接'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLink(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            addLink(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const remark = row.linkName || ''
      this.$modal.confirm('是否确认删除友情链接' + remark + '？').then(function() {
        return delLink(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('blog/link/export', {
        ...this.queryParams
      }, `link_${new Date().getTime()}.xlsx`)
    },
    /** 图片上传前的校验 */
    beforeImageUpload(file) {
      const isJPEG = file.name.split('.')[1] === 'jpeg'
      const isJPG = file.name.split('.')[1] === 'jpg'
      const isPNG = file.name.split('.')[1] === 'png'
      const isBMP = file.name.split('.')[1] === 'bmp'
      const isGIF = file.name.split('.')[1] === 'gif'
      const isLt500K = file.size / 1024 / 500 < 1
      if (!isJPG && !isJPEG && !isPNG && !isBMP && !isGIF) {
        this.$message.error('上传图片只能是 JPEG/JPG/PNG/BMP/GIF 格式!')
        return false
      }
      if (!isLt500K) {
        this.$message.error('单张图片大小不能超过 500KB!')
        return false
      }
      return (isJPEG || isJPG || isPNG || isBMP || isGIF) && isLt500K
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    /** 文件上传成功后的回调 */
    uploadSuccess(response, file, fileList) {
      this.$message.success(response.msg)
      this.form.linkIconUrl = response.data.url
      this.upload.isUploading = false
    },
    /** 回写图片地址 */
    setImageUrl(url) {
      this.$set(this.form, 'linkIconUrl', url);
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
